const querystring = require("querystring");
const Router = require("koa-router");
const session = require("../utils/session.js");
const request = require("request");
const http = require("../utils/http");



const router = new Router({
    prefix: "/user"
});
router.get("/login/:code",
    async(ctx, next) => {

        let code = ctx.params.code;
        console.log(code);
        let url = "https://api.weixin.qq.com/sns/jscode2session?";
        let params = {
            appid: "wx26112823289bbcae",
            secret: "5a539a11a8d4b1cf811d599431013678",
            js_code: code,
            grant_type: "authorization_code"
        };
        let urlParams = querystring.stringify(params);
        return new Promise((resolve, reject) => {
            request.get({
                url: url + urlParams
            }, async function(error, response, body) {
                if (error) reject(error);
                else {
                    const {
                        openid,
                        session_key
                    } = JSON.parse(body);
                    const str_3rd_session = session.set([openid, session_key]);

                    // 通知数据库 进行添加操作
                    await http('call p_login(?);', [openid]);

                    resolve(str_3rd_session); //token返回到服务器
                }
            })

        })
    });

module.exports = router.routes();